package com.maserb.monitor.web.schoolStudent;

import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.SysCode;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.jwQuestion.JwQuestionItemEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolTimeTableEntity;
import com.maserb.monitor.entity.schoolStudent.StudentAchieveEntity;
import com.maserb.monitor.entity.schoolStudent.StudentScoreEntity;
import com.maserb.monitor.enums.JwQuestionItemTypeEnum;
import com.maserb.monitor.enums.SchoolTimeTableDayEnum;
import com.maserb.monitor.enums.SchoolTimeTypeEnum;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.common.FileService;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.jwQuestion.JwQuestionItemService;
import com.maserb.monitor.service.schoolStudent.SchoolTimeTableService;
import com.maserb.monitor.service.schoolStudent.StudentAchieveService;
import com.maserb.monitor.service.schoolStudent.StudentScoreService;
import com.maserb.monitor.service.sysCode.SysCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 学生考试分数
 */
@Controller
@RequestMapping("/studentScore")
@Slf4j
public class StudentScoreController {
    @Autowired
    JwQuestionItemService jwQuestionItemService;

    @Autowired
    private IToolService toolService;

    @Autowired
    private StudentAchieveService achieveService;

    @Autowired
    private SysCodeService codeService;

    @Autowired
    private StudentScoreService scoreService;

    @Autowired
    private FileService fileService;

    @RequestMapping("/doListScoreItem")
    @ResponseBody
    public PageResponseResult<StudentScoreEntity> doListScoreItem(HttpServletRequest request,PageRequestParam page, final String parentId) {
        return AjaxUtils.processPage(page, new Func_T1<Pageable, Page<StudentScoreEntity>>() {
            @Override
            public Page<StudentScoreEntity> invoke(Pageable var1) throws Exception {
                Page<StudentScoreEntity> page = scoreService.findAllByAchieveId(request,parentId,var1);
                return page;
            }
        });
    }

    @RequestMapping("/getAddScoreItem/{parentId}")
    public ModelAndView getAddScoreItem(@PathVariable String parentId) {
        ModelAndView result = new ModelAndView();
        /*JwQuestionItemTypeEnum[] type = JwQuestionItemTypeEnum.values();
        result.addObject("type",type);*/
        List<SysCode>codeList = codeService.findByParent("SCHOOL_COURSE");
        result.addObject("codeList",codeList);
        result.addObject("parentId", parentId);
        result.setViewName("student_achieve/addItem");
        return result;
    }

    @RequestMapping("/doAddScoreItem")
    @ResponseBody
    public AjaxResult<Boolean> doAddScoreItem(final HttpServletRequest request, StudentScoreEntity entity, String parentId) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                entity.setCreateTime(new Date());
                scoreService.save(entity, parentId);
                scoreService.updateAchieve(parentId);
                return true;
            }
        });
    }

    @RequestMapping("/getUpdateItem/{id}")
    public ModelAndView getUpdateItem(@PathVariable final String id) {
        ModelAndView result = new ModelAndView();
        StudentScoreEntity entity = scoreService.findOne(id);
        result.setViewName("student_achieve/item_edit");
        List<SysCode>codeList = codeService.findByParent("SCHOOL_COURSE");
        result.addObject("codeList",codeList);
        /*JwQuestionItemTypeEnum[] type = JwQuestionItemTypeEnum.values();
        result.addObject("type",type);*/
        result.addObject("entity", entity);
        return result;
    }

    @RequestMapping("/doUpdateItem")
    @ResponseBody
    public AjaxResult<Boolean> doUpdateItem(final HttpServletRequest request, StudentScoreEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                StudentScoreEntity scoreEntity = scoreService.findOne(entity.getId());
                scoreEntity.setScore(entity.getScore());
                scoreEntity.setSubject(entity.getSubject());
                scoreEntity.setDescription(entity.getDescription());
                scoreEntity.setCreateTime(new Date());
                scoreService.save(scoreEntity);
                scoreService.updateAchieve(scoreEntity.getAchieve().getId());
                return true;
            }
        });
    }

    @RequestMapping("/doDeleteItem")
    @ResponseBody
    public AjaxResult<Boolean> doDeleteItem(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                keys.forEach(id->scoreService.delete(id));
                return true;
            }
        });
    }


    @RequestMapping(value = {"/", "/index"})
    public ModelAndView getIndex(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("student_achieve/score_index");
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String userId = user.getId();
        view.addObject("userId",userId);
        return view;
    }

    @RequestMapping("/doListScore")
    @ResponseBody
    public PageResponseResult<StudentScoreEntity> doListScore(HttpServletRequest request,PageRequestParam page, String name,String studentId, final String term, final String clazzId) {
        return AjaxUtils.processPage(page, new Func_T1<Pageable, Page<StudentScoreEntity>>() {
            @Override
            public Page<StudentScoreEntity> invoke(Pageable var1) throws Exception {
                HttpSession session = request.getSession(true);
                UserEntity user = (UserEntity) session.getAttribute("user");
                String userId = user.getId();
                Page<StudentScoreEntity> page = scoreService.findAllByUser(var1,userId,name,studentId,term,clazzId);
                if(null!=page){
                    for(StudentScoreEntity entity : page.getContent()){
                        if(!StringUtils.isEmptyOrWhitespace(entity.getAchieve().getClazzId())){
                            entity.getAchieve().setClazzId(toolService.getOrgName(entity.getAchieve().getClazzId()));
                        }
                        entity.getAchieve().getStudent().setParent(null);
                        entity.getAchieve().getStudent().setMaster(null);
                    }
                }
                return page;
            }
        });
    }

    @RequestMapping("/index_teacher")
    public ModelAndView getIndexTeacher(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("student_achieve/index_teacher");
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String userId = user.getId();
        view.addObject("userId",userId);
        return view;
    }

    @RequestMapping("/updateScoreByAchieveId")
    public void updateScoreByAchieveId(final HttpServletRequest request,String id,String score,String description) {
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String codeId = user.getSysCodeId();
        SysCode subject = new SysCode();
        if(!StringUtils.isEmptyOrWhitespace(codeId)){
            subject = codeService.findOne(codeId);
        }
        if(!StringUtils.isEmptyOrWhitespace(id)){
            StudentAchieveEntity achieveEntity = achieveService.findOne(id);
            StudentScoreEntity scoreEntity = new StudentScoreEntity();
            List<StudentScoreEntity> scoreEntityList = scoreService.findByAchieve(achieveEntity);
            String scoreId = "";
            if(scoreEntityList.size()>0){
                for(StudentScoreEntity entity: scoreEntityList){
                    if(entity.getSubject().equals(subject)){
                        scoreId = entity.getId();
                        scoreEntity = scoreService.findOne(scoreId);
                    }
                }
            }
            scoreEntity.setCreateTime(new Date());
            if(!StringUtils.isEmptyOrWhitespace(description)){
                scoreEntity.setDescription(description);
            }
            if(!StringUtils.isEmptyOrWhitespace(score)){
                try{
                    Long scoreLong = Long.valueOf(score);
                    if(null != scoreLong){
                        scoreEntity.setScore(scoreLong);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            scoreEntity.setAchieve(achieveEntity);
            scoreEntity.setSubject(subject);
            scoreService.save(scoreEntity);
            scoreService.updateAchieve(id);
        }
    }

    @RequestMapping("/getAchieveList")
    @ResponseBody
    public PageResponseResult<StudentAchieveEntity> getAchieveList(HttpServletRequest request,PageRequestParam page,String userId, String name,String studentId, final String term, final String clazzId) {
        return AjaxUtils.processPage(page, new Func_T1<Pageable, Page<StudentAchieveEntity>>() {
            @Override
            public Page<StudentAchieveEntity> invoke(Pageable var1) throws Exception {
                HttpSession session = request.getSession(true);
                UserEntity user = (UserEntity) session.getAttribute("user");
                String userId = user.getId();
                String codeId = user.getSysCodeId();
                SysCode subject = new SysCode();
                if(!StringUtils.isEmptyOrWhitespace(codeId)){
                    subject = codeService.findOne(codeId);
                }
                Page<StudentAchieveEntity> page = achieveService.findAll(var1,userId,name,studentId,term,clazzId);
                if(null!=page){
                    for(StudentAchieveEntity entity : page.getContent()){
                        if(!StringUtils.isEmptyOrWhitespace(entity.getClazzId())){
                            entity.setClazzId(toolService.getOrgName(entity.getClazzId()));
                        }
                        List<StudentScoreEntity> scoreEntityList = scoreService.findByAchieve(entity);
                        entity.setSubjectName(subject.getName());
                        if(scoreEntityList.size()>0){
                            for(StudentScoreEntity scoreEntity: scoreEntityList){
                                if(scoreEntity.getSubject().equals(subject)){
                                    entity.setScore(scoreEntity.getScore());
                                    entity.setDescription(scoreEntity.getDescription());

                                }
                            }
                        }

                    }
                }
                return page;
            }
        });
    }


    @RequestMapping("/uploadScore")
    @ResponseBody
    public AjaxResult<Boolean> uploadScore(MultipartFile uploadFile) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() {
                String ctxPath = fileService.getUploadDir();
                try {
                    File file = new File(ctxPath + File.separator + "scores");
                    if (!file.exists()) {
                        file.mkdir();// 创建文件根目录
                    }
//                    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//                    MultipartFile mf = multipartRequest.getFile("uploadFile");// 获取上传文件对象
                    String fileName = UUID.randomUUID().toString() + ".zip";
                    String savePath = file.getPath() + File.separator + fileName;
                    File saveFile = new File(savePath);
                    FileCopyUtils.copy(uploadFile.getBytes(), saveFile);
                    return true;
                } catch (IOException e) {
                    log.error("upload error : " + e.getMessage());
                    return false;
                }
            }
        });
    }
}
